from socket import *
from multiprocessing import Process
from dict_db import *


class Handle(Process):
    def __init__(self, conn):
        self.conn = conn
        self.db = Dict()
        super().__init__()

    # 循环接收请求，分情况讨论
    def run(self):
        while True:
            request = self.conn.recv(1024)
            tmp = request.decode().split("\t")
            if tmp[0] == 'R':
                # tmp[1]是名字,tmp[2]是密码
                self.do_register(tmp[1], tmp[2])
            elif tmp[0] == 'L':
                # tmp[1]是名字,tmp[2]是密码
                self.do_login(tmp[1], tmp[2])
            elif tmp[0] == 'Q':
                self.do_query(tmp[1])
        self.db.close()
        self.conn.close()

    def do_register(self, name, passwd):
        if self.db.register(name, passwd):
            self.conn.send(b'T')
        else:
            self.conn.send(b'F')

    def do_login(self, name, passwd):
        if self.db.login(name, passwd):
            self.conn.send(b'T')
        else:
            self.conn.send(b'F')

    def do_query(self, word):
        mean = self.db.query(word)
        if mean:
            res = "T\t" + mean[0]
            self.conn.send(res.encode())
            self.db.insert_hist()  # 历史记录
        else:
            self.conn.send(b'F')


class DictServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._creat_socket()

    def serve_forever(self):
        self.sock.listen(5)
        print("listen the port %d" % self.port)
        while True:
            conn, addr = self.sock.accept()
            print("connect from", addr)
            handle = Handle(conn)
            handle.start()

    def _creat_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock


if __name__ == '__main__':
    dict = DictServer(host="0.0.0.0", port=8888)
    dict.serve_forever()
